package com.example.ndkdemotest

import android.app.Activity
import android.os.Bundle
import android.view.View
import android.widget.ScrollView
import android.widget.Toast
import androidx.databinding.DataBindingUtil
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.list.listItems
import com.czb.wisdomcashier.utils.FccUtils
import com.example.ndkdemotest.databinding.ActivityMainBinding
import java.text.SimpleDateFormat
import java.util.*

class MainActivity : Activity() {

    companion object {
        init {
            System.loadLibrary("native-lib")
        }
    }
    private val fcc by lazy { FccUtils.instance }
    private var mdcNO = 1
    private lateinit var curMdc: MdcBean;
    private val mdcArray = arrayListOf(
        MdcBean("192.168.1.35", "6000", "未知", "未知命令", "", "4", "1", "", "", "", "1"),
        MdcBean("127.0.0.1", "6000", "未知", "未知命令", "", "1", "1", "", "", "", "1"),
        MdcBean("192.168.1.88", "6000", "未知", "未知命令", "", "1", "1", "", "", "", "1"),
        MdcBean("192.168.2.254", "6000", "未知", "未知命令", "", "1", "1", "", "", "", "1")
    )
    private lateinit var mBinding: ActivityMainBinding;

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        fcc.initNdk()
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_main)
        mBinding.radioGroup.setOnCheckedChangeListener { radioGroup, i ->
            when (i) {
                R.id.radio_mdc1 -> {
                    mdcNO = 1
                }
                R.id.radio_mdc2 -> {
                    mdcNO = 2
                }
                R.id.radio_mdc3 -> {
                    mdcNO = 3
                }
                R.id.radio_mdc4 -> {
                    mdcNO = 4
                }
            }
            //切换数据源
            curMdc = mdcArray[mdcNO - 1]
            mBinding.setVariable(BR.data, curMdc)
            mBinding.executePendingBindings()
        }
        //切换数据源
        curMdc = mdcArray[0]
        mBinding.setVariable(BR.data, curMdc)
        mBinding.executePendingBindings()
        hideEdit()
    }



    fun onExecute(v: View) {
        fcc.apply {
            when (mBinding.tvMdcCmd.text) {
                "查时间" -> { QryMDCTime(mdcNO) }
                "设置时间" -> { setMdcTime() }
                "查油品" -> { QryNZLOilInfo(mdcNO, curMdc.ChlNo.toInt(), curMdc.NZL.toInt()) }
                "设油品" -> { SetNZLOilInfo(mdcNO, curMdc.ChlNo.toInt(), curMdc.NZL.toInt(), curMdc.oilCode.toInt(), curMdc.oilPrice.toInt(), curMdc.oilDensity.toInt()) }
                "查泵码" -> { QryVTOT(mdcNO, curMdc.ChlNo.toInt(), curMdc.NZL.toInt()) }
                "查交易" -> { QryTTC(mdcNO, curMdc.ChlNo.toInt(), curMdc.oilTtc.toInt()) }
                "查最大ttc" -> { getMaxTTC(mdcNO, curMdc.ChlNo.toInt(), curMdc.NZL.toInt()) }
                "设时段" -> { //todo
                    setAuthCfg(mdcNO, 1, 1, 8, 22, 2, 2)
                }
                "查时段" -> { getAuthCfg(mdcNO, curMdc.ChlNo.toInt(), curMdc.NZL.toInt()) }
                "授权" -> { gunAuth(mdcNO, curMdc.ChlNo.toInt(), curMdc.NZL.toInt()) }
                "取消授权" -> { gunCancelAuth(mdcNO, curMdc.ChlNo.toInt(), curMdc.NZL.toInt()) }
                "查设备sn" -> { QryDevInfo(mdcNO) }
            }
        }
        Toast.makeText(this, "${mBinding.tvMdcCmd.text}", Toast.LENGTH_SHORT).show()
    }

    /**
     *  显示输入区域 设置时段暂未实现
     */
    fun showCmdSelect(v: View) {
        MaterialDialog(this).show {
            listItems(R.array.socialNetworks) { _, index, text ->
                mBinding.tvMdcCmd.text = text
                hideEdit()
                when (mBinding.tvMdcCmd.text) {
                    "设置时间" -> { mBinding.tvSelectTime.visibility = View.VISIBLE
                    }
                    "设油品" -> {
                        mBinding.edOilCode.visibility = View.VISIBLE
                        mBinding.edPrice.visibility = View.VISIBLE
                        mBinding.edDensity.visibility = View.VISIBLE
                        mBinding.tvOilCode.visibility = View.VISIBLE
                        mBinding.tvPrice.visibility = View.VISIBLE
                        mBinding.tvDensity.visibility = View.VISIBLE
                    }
                    "查交易" -> {
                        mBinding.edTtc.visibility = View.VISIBLE
                        mBinding.tvTtc.visibility = View.VISIBLE
                    }
                    "设时段" -> {
                        //TODO
                    }
                    else -> { onExecute(v) }
                }
            }
        }
    }

    private fun hideEdit() {
        mBinding.tvSelectTime.visibility = View.GONE

        mBinding.edOilCode.visibility = View.GONE
        mBinding.tvOilCode.visibility = View.GONE
        mBinding.edPrice.visibility = View.GONE
        mBinding.tvPrice.visibility = View.GONE
        mBinding.edDensity.visibility = View.GONE
        mBinding.tvDensity.visibility = View.GONE

        mBinding.tvTtc.visibility = View.GONE
        mBinding.edTtc.visibility = View.GONE
    }

    fun showChlSelect(v: View) {
        MaterialDialog(this).show {
            listItems(R.array.numArray) { _, index, text ->
                mBinding.tvChlNo.text = text
            }
        }
    }

    fun showNZLSelect(v: View) {
        MaterialDialog(this).show {
            listItems(R.array.numArray) { _, index, text ->
                mBinding.tvNzl.text = text
            }
        }
    }

    fun setMdcTime(){
        try {
            SimpleDateFormat("yyyy-MM-dd kk:mm:ss").parse(mBinding.tvSelectTime.text.toString()).apply {
                val ca = Calendar.getInstance()
                ca.time = this
                ca.apply {
                    val log= fcc.SetMDCTime(
                        mdcNO,
                        get(Calendar.YEAR), get(Calendar.MONTH) + 1, get(Calendar.DATE),
                        get(Calendar.HOUR_OF_DAY), get(Calendar.MINUTE), get(Calendar.SECOND)
                    )
                    addLog(
                        "下发油机时间: " + "${if (log == 0) "(成功)" else if (log == 2) "(当前MDC未注册)" else if (log == 3) "IP或端口无效" else "未知错误"}" +
                                "${get(Calendar.YEAR)}-${get(Calendar.MONTH) + 1}-${get(Calendar.DATE)} " +
                                "${get(Calendar.HOUR_OF_DAY)}:${get(Calendar.MINUTE)}:${get(Calendar.SECOND)}"
                    )
                }
            }
        } catch (e: Exception) {
            Toast.makeText(this, "格式一定要正确输入 ${e.toString()}", Toast.LENGTH_SHORT).show()
        }
    }

    // <editor-fold defaultstate="collapsed" desc="fcc方法">
    fun RegMDC(v: View) {
        val log = fcc.RegMDC(mdcNO)
        addLog(if (log == 0) "RegMDC 成功" else "RegMDC 失败")
    }

    fun UnregMDC(v: View) {
        val log = fcc.UnregMDC(mdcNO)
        addLog(if (log == 0) "UnregMDC 成功" else "MDC UnregMDC 失败")
    }

    fun RegNotifyEventCallback(v: View) {
        val log = fcc.RegNotifyEventCallback(mdcNO)
        addLog(if (log == 0) "MDC注册事件回调成功" else "MDC注册事件回调失败")
    }

    fun RegErrCallback(v: View) {
        val log = fcc.RegErrCallback(mdcNO)
        addLog(if (log == 0) "MDC注册错误回调成功" else "MDC注册错误回调失败")
    }

    fun MDCInit(v: View) {
        val log = fcc.MDCInit(mdcNO, curMdc.ip, curMdc.port.toInt())
        addLog(if (log == 0) "MDC初始化成功" else if (log == 2) "当前MDC未注册" else if (log == 3) "IP或端口无效" else if (log == 4) "MDC工作中不能重复初始化" else "未知错误")
    }

    fun startWork(v: View){
        val log = fcc.startWork(mdcNO)
        addLog(if (log == 0) "启动成功" else if (log == 1) "已启动" else "启动失败($log)")
    }

    fun StopWork(v: View){
        val log = fcc.StopWork(mdcNO)
        addLog(if (log == 0) "关闭成功" else "关闭失败")
    }

    fun reStart(v: View){
        val log = fcc.reStart(mdcNO)
        addLog(if (log == 0) "reStart成功" else "reStart失败")
    }

    // </editor-fold>

    fun showSelectTime(v: View){
        // android:focusable="false" 双击获取当前时间
        mBinding.tvSelectTime.setText("${Calendar.getInstance().formatDateTime()}")
    }

    fun Calendar.formatDateTime(): String {
        return SimpleDateFormat("yyyy-MM-dd kk:mm:ss").format(time)
    }

    fun clearLog(v: View) {
        curMdc.log = ""
        mBinding.tvLog.text = ""
    }

    private fun addLog(s: String){
        curMdc.log = curMdc.log + s + "\n"
        mBinding.tvLog.text = curMdc.log
        mBinding.scrollView.fullScroll(ScrollView.FOCUS_DOWN)
    }

    private fun addLog(s: String, rep: String) {
        curMdc.log = curMdc.log + s + "\n"
        mBinding.tvLog.text = curMdc.log
    }
}